package com.itheima.controller;

import com.itheim.client.pojo.User;
import com.itheima.common.R;
import com.itheima.service.LoginService;
import com.itheima.util.RequestParesUtil;
import com.itheima.util.SendSms;
import com.itheima.util.ValidateCodeUtils;
import com.sun.org.apache.bcel.internal.classfile.Code;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @Author longbosheng
 * @Date 2022/6/19 14:10
 * @PackageName:com.itheima.controller
 * @ClassName: LoginController
 * @Description: TODO
 * @Version 1.0
 */
@Log4j2
@RestController
@RequestMapping("/user")
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 用户登录
     *
     * @param user
     * @return
     */
    @PostMapping("/login")
    public R Login(@RequestBody User user) {
        R loginresult = loginService.login(user);
        return loginresult;
    }

    /**
     * 发送短信
     *
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R sendMessage(@RequestBody User user) {
        //获取手机号
            String phone = user.getPhone();
            //判断手机号是否为空
            if(!StringUtils.isEmpty(phone)){
                //若存在，生成一个随机4位验证码
                String code = String.valueOf(ValidateCodeUtils.generateValidateCode(4));
                log.info("code= {}",code);
//                发送验证码
//                SendSms.send(phone,code);
//                将验证码存入到redis中
                redisTemplate.opsForValue().set(phone, code,60, TimeUnit.SECONDS);
                return R.success("验证码发送成功");
            }
            return R.error("验证码发送失败");
    }

    /**
     * 登出
     *
     * @param request
     * @return
     */
    @PostMapping("/loginout")
    public R logout(HttpServletRequest request) {
        String token = request.getHeader("AuthorizationUser");
        if (token == null) {
            return R.success("退出成功(token内容为空)");
        }
        Boolean delete = redisTemplate.delete(token);
        if (delete) {
            return R.success("退出成功");
        }
        return R.success("没有token直接退出");
    }
}
